import {
  loginByPhone,
  loginByEmail,
  logout,
  getInfo,
  getMenus
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken,
  getPlatformId,
  setPlatformId,
  removePlatformId
} from '@/utils/auth'
import {
  Message
} from 'element-ui'
const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    username: '',
    introduction: '',
    roles: [],
    menus: undefined,
    eleemnts: undefined,
    permissionMenus: undefined,
    setting: {
      articlePlatform: []
    },
    userId: undefined,
    platformId: undefined,
    merchantId: undefined,
    skinStyle: undefined,
    userphone: undefined
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_PLATFORMID: (state, platformId) => {
      state.platformId = platformId
    },
    SET_MERCHANTID: (state, merchantId) => {
      state.merchantId = merchantId
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.username = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_ELEMENTS: (state, elements) => {
      state.elements = elements
    },
    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user = ''
    },
    SET_PERMISSION_MENUS: (state, permissionMenus) => {
      state.permissionMenus = permissionMenus
    },
    SET_SKIN: (state, skinStyle) => {
      state.skinStyle = skinStyle
    },
    SET_PHONE: (state, userphone) => {
      state.userphone = userphone
    }
  },

  actions: {
    // 邮箱登录
    LoginByEmail({
      commit
    }, userInfo) {
      const username = userInfo.username.trim()
      const imagecode = ""
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENUS', undefined)
      commit('SET_ELEMENTS', undefined)
      commit('SET_NAME', username)
      removeToken()
      return new Promise((resolve, reject) => {
        loginByEmail(username, userInfo.password, imagecode).then(response => {
          const result = response
          console.log('登陆接口')
          console.log(result)
          if (result.code !== '0000') {
            Message({
              message: result.message,
              type: 'warning'
            })
            return Promise.reject('error')
          } else {
            console.log('登陆成功')
            setPlatformId(result.data.platformId)
            setToken(result.data.token)
            commit('SET_TOKEN', result.data.token)
            commit('SET_SKIN', result.data.skinStyle)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 校验手机验证码并登录
    LoginByPhone({
      commit
    }, userInfo) {
      const phone = userInfo.mobile.trim()
      const code = userInfo.code.trim()
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENUS', undefined)
      commit('SET_ELEMENTS', undefined)
      commit('SET_PHONE', phone)
      removeToken()
      return new Promise((resolve, reject) => {
        loginByPhone(phone, code).then(response => {
          const data = response
          if (data.code !== '0000') {
            Message({
              message: data.message,
              type: 'warning'
            })
            return Promise.reject('error')
          } else {
            setPlatformId(response.platformId)
            setToken(response.token)
            commit('SET_TOKEN', response.token)
            commit('SET_SKIN', response.skinStyle)
            commit('SET_NAME', response.username)
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          console.log('获取用户信息')
          console.log(response)
          const result = response
          commit('SET_ROLES', 'admin')
          commit('SET_USERID', response.data.userId)
          commit('SET_PLATFORMID', response.data.platformId)
          commit('SET_MERCHANTID', response.data.merchantId)
          commit('SET_AVATAR', 'http://git.oschina.net/uploads/42/547642_geek_qi.png?1499487420')
          commit('SET_INTRODUCTION', response.data.description)
          commit('SET_PHONE', response.data.mobilePhone)
          const menus = {}
          for (let i = 0; i < response.data.menus.length; i++) {
            menus[response.data.menus[i].code] = true
          }
          commit('SET_MENUS', menus)
          const elements = {}
          for (let i = 0; i < response.data.elements.length; i++) {
            elements[response.data.elements[i].code] = true
          }
          commit('SET_ELEMENTS', elements)
          resolve(response.data)
        }).catch(error => {
          reject(error)
        })
        getMenus(state.token).then(response => {
          console.log('SET_PERMISSION_MENUS')
          console.log(response.data)
          commit('SET_PERMISSION_MENUS', response.data)
        })
      })
    },

    // 第三方验证登录
    /* LoginByThirdparty({
      commit,
      state
    }, code) {
      return new Promise((resolve, reject) => {
        commit('SET_CODE', code)
        loginByThirdparty(state.status, state.email, state.code).then(response => {
          commit('SET_TOKEN', response.data.token)
          setToken(response.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }, */

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_MENUS', undefined)
          commit('SET_ELEMENTS', undefined)
          commit('SET_PERMISSION_MENUS', undefined)
          removeToken()
          removePlatformId()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_MENUS', undefined)
        commit('SET_ELEMENTS', undefined)
        commit('SET_PERMISSION_MENUS', undefined)
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRole({
      commit
    }, role) {
      return new Promise(resolve => {
        commit('SET_ROLES', [role])
        commit('SET_TOKEN', role)
        setToken(role)
        resolve()
      })
    }
  }
}

export default user
